<template>
  <div class="del">
    <div class="left">
      <el-tree
        :data="data"
        :props="props"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        @check-change="handleCheckChange"
        ref="treeRef"
      />
    </div>
    <div class="center">
      <div class="jt" @click="add">></div>
      <div class="jt"><</div>
    </div>
    <div class="right">
      <el-tree
        :data="data1"
        :props="props"
        node-key="id"
        :default-expand-all="true"
        ref="treeRef1"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ data.name }}</span>
            <span class="r">
              <el-input-number
                v-model="data.num"
                size="small"
                v-if="!data.children"
              ></el-input-number>
              <a style="margin-left: 8px" @click.stop="remove(node, data)">
                删除
              </a>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, inject } from "vue";
import { useRoute, useRouter } from "vue-router";
const props = {
  label: "name",
  children: "children",
};
const data = ref([
  {
    name: "卫星",
    id: 1,
    children: [
      {
        name: "电子侦察卫星",
        id: 11,
        pid: 1,
      },
      {
        name: "图像侦察卫星",
        id: 12,
        pid: 1,
      },
      {
        name: "通信卫星",
        id: 13,
        pid: 1,
      },
      {
        name: "导航卫星",
        id: 14,
        pid: 1,
      },
      {
        name: "测绘卫星",
        id: 15,
        pid: 1,
      },
      {
        name: "电子对抗卫星",
        id: 16,
        pid: 1,
      },
    ],
  },
  {
    name: "导弹车",
    id: 2,
    children: [
      {
        name: "导弹车1",
        id: 21,
        pid: 2,
      },
      {
        name: "导弹车2",
        id: 22,
        pid: 2,
      },
    ],
  },
  {
    name: "飞机",
    id: 3,
    children: [
      {
        name: "飞机1",
        pid: 3,
        id: 31,
      },
      {
        name: "飞机2",
        id: 32,
        pid: 3,
      },
    ],
  },
]);

const data1 = ref([]);
const treeRef = ref(null);
const treeRef1 = ref(null);
const handleCheckChange = (data, checked, indeterminate) => {};

const checkedNodes = ref([]);
const unCheckedNodes = ref([]);
function setSelect(arr, ids) {
  arr.forEach((v) => {
    if (ids.includes(v.id)) {
      v.select = true;
    } else {
      v.select = false;
    }
    if (v.children && v.children.length) {
      setSelect(v.children, ids);
    }
  });
}
function removeFalseSelectItems(arr) {
  let arr1 = JSON.parse(JSON.stringify(arr));
  return arr1.reduce((acc, item) => {
    if (item.select !== false) {
      if (Array.isArray(item.children)) {
        // 递归处理子数组
        item.children = removeFalseSelectItems(item.children);
        // 如果子数组之后不为空，则保留该项
        if (item.children.length > 0) {
          acc.push(item);
        }
      } else {
        // 没有子数组，直接保留该项
        acc.push(item);
      }
    }
    return acc;
  }, []);
}

function treeFilter(tree, func) {
  return tree
    .map((node) => ({ ...node }))
    .filter((node) => {
      node.children = node.children && treeFilter(node.children, func);
      return func(node) || (node.children && node.children.length);
    });
}
const add = () => {
  console.log(treeRef.value.getCheckedNodes());
  console.log(treeRef.value.getCheckedKeys());
  // 最简单
  let ids = treeRef.value.getCheckedKeys();
  data1.value = treeFilter(data.value, (node) => ids.includes(node.id));

  // checkedNodes.value = treeRef.value
  //   .getCheckedNodes()
  //   //过滤掉父节点，并且只取的id
  //   .filter((item) => !item.children || item.children.length === 0)
  //   .map((item) => item.id);
  // console.log("已勾选的复选框为", checkedNodes.value);

  // // 通过服务端拿到的数据dataSource.value，获取所有子节点的 ID，过滤父节点的数据
  // const allChildIds = data.value.flatMap((parentNode) =>
  //   parentNode.children && parentNode.children.length > 0
  //     ? parentNode.children.map((childNode) => childNode.id)
  //     : []
  // );

  // // 创建一个包含勾选节点 ID 的 Set
  // const checkedNodeSet = new Set(checkedNodes.value);

  // // 计算未勾选的节点 ID
  // unCheckedNodes.value = allChildIds.filter((id) => !checkedNodeSet.has(id));
  // console.log("未勾选的", unCheckedNodes.value);

  // 好用的

  //   const getC = treeRef.value.getCheckedNodes(false, true);
  //   const getHC = treeRef.value.getHalfCheckedNodes();
  //   let selected_nodes = getHC.concat(getC);
  //   let selected_ids = new Set(); // 记录选中的节点tree_id
  //   let used_ids = new Set(); // 记录已经查询过的节点
  //   // 遍历初始化selected_ids
  //   for (let node of selected_nodes) {
  //     selected_ids.add(node.$treeNodeId);
  //   }
  //   // 最终的结果数据用一个根节点存储, 为了对齐递归的数据结构
  //   let root_node = {
  //     treeNodeId: -1,
  //     children: [],
  //   };
  //   // 添加给parent_node节点一个新节点 node
  //   // 注意:node 的类型是原始的 tree 节点
  //   // 而parent_node 的类型是真正的结果节点
  //   function AddNode(node, parent_node) {
  //     if (!selected_ids.has(node.$treeNodeId) || used_ids.has(node.$treeNodeId)) {
  //       return;
  //     }
  //     used_ids.add(node.$treeNodeId); // 加过的要存入 used_ids 做标记
  //     let real_node = {
  //       treeNodeId: node.$treeNodeId,
  //       children: [],
  //       name: node.name,
  //       id: node.id,
  //       // 存储一下节点的数据
  //     };
  //     // // 添加子节点
  //     if (node.children) {
  //       for (let child_node of node.children) {
  //         AddNode(child_node, real_node);
  //       }
  //     }
  //     if (real_node.children.length === 0) {
  //       delete real_node.children;
  //     }
  //     if (!real_node.grade) {
  //       delete real_node.grade;
  //     }
  //     if (!real_node.desc) {
  //       delete real_node.desc;
  //     }
  //     parent_node.children.push(real_node);
  //   }
  //   for (let node of selected_nodes) {
  //     AddNode(node, root_node);
  //   }
  //  data1.value = root_node.children;

  // 简单
  // let halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  // let halfCheckedKeys1 = treeRef.value.getCheckedKeys();
  // let ids = [];
  // ids = halfCheckedKeys.concat(halfCheckedKeys1);
  // setSelect(data.value, ids);
  // data1.value = removeFalseSelectItems(data.value);
};

const remove = (node, data) => {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id === data.id);
  children.splice(index, 1);
  data1.value = [...data1.value];
  console.log(data1.value);
};

onMounted(() => {});
</script>
<style scoped lang="scss">
.del {
  width: 100%;
  height: 100%;

  display: flex;
  .center {
    width: 2%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .jt {
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background: #14384e;
      border: 1px solid #5099a7;
      margin: 10px 0;
    }
  }
  .left,
  .right {
    width: 48%;
    border: 1px solid red;
  }
}
:deep() {
  .el-tree {
    width: 100%;
    height: 100%;
    .custom-tree-node {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      .r {
        text-align: right;
        display: inline-block;
        width: 200px;
        float: right;
      }
    }
  }
}
</style>
